package com.luxsoft.sw3.replica;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.hibernate.CallbackException;
import org.hibernate.EmptyInterceptor;
import org.hibernate.Session;
import org.hibernate.type.Type;

/**
 * Interceptor general para las operaciones sel sistema
 * 
 * @author Ruben Cancino Ramos
 * 
 */
public class SXInterceptor extends EmptyInterceptor {

	private Session session;
	private Long userId;
	private Set inserts = new HashSet();
	private Set updates = new HashSet();
	private Set deletes = new HashSet();

	public void setUserId(Long userId) {
		this.userId = userId;
	}

	public boolean onSave(Object entity, Serializable id, Object[] state,
			String[] propertyNames, Type[] types) throws CallbackException {
		if (entity instanceof Replicable)
			inserts.add(entity);
		return false;
	}

	public boolean onFlushDirty(Object entity, Serializable id,
			Object[] currentState, Object[] previousState,
			String[] propertyNames, Type[] types) throws CallbackException {
		if (entity instanceof Replicable)
			updates.add(entity);
		return false;
	}

	@Override
	public void postFlush(Iterator entities) {

		try {
			for (Iterator it = inserts.iterator(); it.hasNext();) {
				Replicable entity = (Replicable) it.next();
				//AuditLog.logEvent("create", entity, userId, session.connection());
			}
			for (Iterator it = updates.iterator(); it.hasNext();) {
				Replicable entity = (Replicable) it.next();
				//AuditLog.logEvent("update", entity, userId, session.connection());
			}
		} finally {
			inserts.clear();
			updates.clear();
		}
	}

}
